{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a8b892c8",
   "metadata": {},
   "source": [
    "Printed and electronic copies of *Modeling and Simulation in Python* are available from [No Starch Press](https://nostarch.com/modeling-and-simulation-python) and [Bookshop.org](https://bookshop.org/p/books/modeling-and-simulation-in-python-allen-b-downey/17836697?ean=9781718502161) and [Amazon](https://amzn.to/3y9UxNb)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "mighty-israeli",
   "metadata": {},
   "source": [
    "# Case Studies Part 2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "imported-table",
   "metadata": {
    "tags": []
   },
   "source": [
    "*Modeling and Simulation in Python*\n",
    "\n",
    "Copyright 2021 Allen Downey\n",
    "\n",
    "License: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "formal-context",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# download modsim.py if necessary\n",
    "\n",
    "from os.path import basename, exists\n",
    "\n",
    "def download(url):\n",
    "    filename = basename(url)\n",
    "    if not exists(filename):\n",
    "        from urllib.request import urlretrieve\n",
    "        local, _ = urlretrieve(url, filename)\n",
    "        print('Downloaded ' + local)\n",
    "    \n",
    "download('https://raw.githubusercontent.com/AllenDowney/' +\n",
    "         'ModSimPy/master/modsim.py')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "progressive-typing",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# import functions from modsim\n",
    "\n",
    "from modsim import *"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dense-seattle",
   "metadata": {
    "tags": []
   },
   "source": [
    "This chapter is available as a Jupyter notebook where you can read the text, run the code, and work on the exercises. \n",
    "Click here to access the notebooks: <https://allendowney.github.io/ModSimPy/>."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "reflected-sitting",
   "metadata": {},
   "source": [
    "This chapter presents case studies where you can apply the tools we have learned so far to the glucose-insulin minimal model, an electronic circuit, a thermal model of a wall, and the interaction of HIV and T cells."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "structured-satellite",
   "metadata": {},
   "source": [
    "## The Glucose Minimal Model\n",
    "\n",
    "In the previous chapter we implemented the glucose minimal model using given parameters, but I didn't say where those parameters came from.\n",
    "\n",
    "In the repository for this book, you will find a notebook,\n",
    "*glucose.ipynb*, that shows how we can find the parameters that best fit the data.\n",
    "You can download it from <https://github.com/AllenDowney/ModSimPy/raw/master/examples/glucose.ipynb> or run it on Colab at <https://colab.research.google.com/github/AllenDowney/ModSimPy/blob/master/examples/glucose.ipynb>.\n",
    "\n",
    "It uses a SciPy function called `leastsq`, which stands for \"least squares\"; so-named because it finds the parameters that minimize the sum of squared differences between the results of the model and the data.\n",
    "\n",
    "You can think of `leastsq` as an optional tool for this book.  We won't use it in the text itself, but it appears in a few of the case studies."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "laden-gathering",
   "metadata": {},
   "source": [
    "## The Insulin Minimal Model\n",
    "\n",
    "Along with the glucose minimal model, Berman et al. developed an insulin minimal model, in which the concentration of insulin, $I$, is governed by this differential equation:\n",
    "\n",
    "$$\\frac{dI}{dt} = -k I(t) + \\gamma \\left[ G(t) - G_T \\right] t$$ \n",
    "\n",
    "where\n",
    "\n",
    "-   $k$ is a parameter that controls the rate of insulin disappearance\n",
    "    independent of blood glucose.\n",
    "\n",
    "-   $G(t)$ is the measured concentration of blood glucose at time $t$.\n",
    "\n",
    "-   $G_T$ is the glucose threshold; when blood glucose is above this\n",
    "    level, it triggers an increase in blood insulin.\n",
    "\n",
    "-   $\\gamma$ is a parameter that controls the rate of increase (or\n",
    "    decrease) in blood insulin when glucose is above (or below) $G_T$.\n",
    "\n",
    "The initial condition is $I(0) = I_0$. As in the glucose minimal model, we treat this initial concentration as a free parameter; that is, we'll choose it to fit the data."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "interstate-gibson",
   "metadata": {},
   "source": [
    "The parameters of this model can be used to estimate $\\phi_1$ and\n",
    "$\\phi_2$, which are quantities that \"describe the sensitivity to glucose of the first and second phase pancreatic responsivity\". These quantities are related to the parameters as follows:\n",
    "\n",
    "$$\\phi_1 = \\frac{I_{max} - I_b}{k (G_0 - G_b)}$$\n",
    "\n",
    "$$\\phi_2 = \\gamma \\times 10^4$$ \n",
    "\n",
    "where $I_{max}$ is the maximum measured insulin level, and $I_b$ and $G_b$ are the basal levels of insulin and glucose.\n",
    "\n",
    "In the repository for this book, you will find a notebook,\n",
    "*insulin.ipynb*, that contains starter code for this case study. Use it to implement the insulin model, find the parameters that best fit the data, and estimate $\\phi_1$ and $\\phi_2$.\n",
    "You can download it from <https://github.com/AllenDowney/ModSimPy/raw/master/examples/insulin.ipynb> or run it on Colab at <https://colab.research.google.com/github/AllenDowney/ModSimPy/blob/master/examples/insulin.ipynb>."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hybrid-vienna",
   "metadata": {},
   "source": [
    "## Low-pass Filter\n",
    "\n",
    "The following circuit diagram (from <https://commons.wikimedia.org/wiki/File:1st_Order_Lowpass_Filter_RC.svg>) shows a low-pass filter built with one resistor and one capacitor.\n",
    "\n",
    "![Circuit diagram of a low-pass filter](https://github.com/AllenDowney/ModSim/raw/main/figs/Lowpass_Filter_RC.png)\n",
    "\n",
    "A *filter* is a circuit that takes a signal, $V_{in}$, as input and produces a signal, $V_{out}$, as output. In this context, a *signal* is a voltage that changes over time.\n",
    "\n",
    "A filter is *low-pass* if it allows low-frequency signals to pass from\n",
    "$V_{in}$ to $V_{out}$ unchanged, but it reduces the amplitude of\n",
    "high-frequency signals."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "visible-estonia",
   "metadata": {},
   "source": [
    "By applying the laws of circuit analysis, we can derive a differential\n",
    "equation that describes the behavior of this system. By solving the\n",
    "differential equation, we can predict the effect of this circuit on any input signal.\n",
    "\n",
    "Suppose we are given $V_{in}$ and $V_{out}$ at a particular instant in\n",
    "time. By Ohm's law, which is a simple model of the behavior of\n",
    "resistors, the instantaneous current through the resistor is:\n",
    "\n",
    "$$I_R = (V_{in} - V_{out}) / R$$ \n",
    "\n",
    "where $R$ is resistance in ohms ($\\Omega$).\n",
    "\n",
    "Assuming that no current flows through the output of the circuit,\n",
    "Kirchhoff's current law implies that the current through the capacitor\n",
    "is: \n",
    "\n",
    "$$I_C = I_R$$ "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "parallel-radical",
   "metadata": {},
   "source": [
    "According to a simple model of the behavior of\n",
    "capacitors, current through the capacitor causes a change in the voltage across the capacitor: \n",
    "\n",
    "$$I_C = C \\frac{d V_{out}}{dt}$$ \n",
    "\n",
    "where $C$ is capacitance in farads (F). Combining these equations yields a differential equation for $V_{out}$:\n",
    "\n",
    "$$\\frac{d V_{out}}{dt} = \\frac{V_{in} - V_{out}}{R C}$$ \n",
    "\n",
    "In the repository for this book, you will find a notebook, *filter.ipynb*, which contains starter code for this case study. You can download it from <https://github.com/AllenDowney/ModSimPy/raw/master/examples/filter.ipynb> or run it on Colab at <https://colab.research.google.com/github/AllenDowney/ModSimPy/blob/master/examples/filter.ipynb>.\n",
    "Follow the instructions to simulate the low-pass filter for input signals like this:\n",
    "\n",
    "$$V_{in}(t) = A \\cos (2 \\pi f t)$$ \n",
    "\n",
    "where $A$ is the amplitude of the input signal, say 5 V, and $f$ is the frequency of the signal in Hz."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "violent-directive",
   "metadata": {},
   "source": [
    "## Thermal Behavior of a Wall\n",
    "\n",
    "This case study is based on a paper that models the thermal behavior of a brick wall with the goal of understanding the \"performance gap between the expected energy use of buildings and their measured energy use\".\n",
    "\n",
    "The following figure shows the scenario and their model of the wall:\n",
    "\n",
    "![Model of a wall as a series of thermal insulators](https://github.com/AllenDowney/ModSim/raw/main/figs/wall_model.png)\n",
    "\n",
    "On the interior and exterior surfaces of the wall, they measure\n",
    "temperature and heat flux (rate of heat flow) over a period of three days. They model the wall using two thermal masses connected to the surfaces, and to each other, by thermal resistors."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "entire-stations",
   "metadata": {},
   "source": [
    "The primary methodology of the paper is a statistical method for inferring the parameters of the system (two thermal masses and three thermal resistances).\n",
    "\n",
    "The primary result is a comparison of two models: the one shown here with two thermal masses, and a simpler model with only one thermal mass. They find that the two-mass model is able to reproduce the measured fluxes substantially better.\n",
    "\n",
    "For this case study we will implement their model and run it with the\n",
    "estimated parameters from the paper, and then use `leastsq` to see\n",
    "if we can find parameters that yield lower errors.\n",
    "\n",
    "In the repository for this book, you will find a notebook, *wall.ipynb* with the code and results for this case study.\n",
    "You can download it from <https://github.com/AllenDowney/ModSimPy/raw/master/examples/wall.ipynb> or run it on Colab at <https://colab.research.google.com/github/AllenDowney/ModSimPy/blob/master/examples/wall.ipynb>.\n",
    "\n",
    "The paper this case study is based on is\n",
    "Gori, Marincioni, Biddulph, Elwell, \"Inferring the thermal resistance and effective thermal mass distribution of a wall from in situ measurements to characterise heat transfer at both the interior and exterior surfaces\", *Energy and Buildings*, 2017, available from <http://modsimpy.com/wall2>.\n",
    "\n",
    "The authors put their paper under a Creative Commons license and made their data available at <http://modsimpy.com/wall>. I thank them for their commitment to open, reproducible science, which made this case study possible."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "duplicate-joshua",
   "metadata": {},
   "source": [
    "## HIV\n",
    "\n",
    "During the initial phase of HIV infection, the concentration of the virus in the bloodstream typically increases quickly and then decreases.\n",
    "The most obvious explanation for the decline is an immune response that destroys the virus or controls its replication.\n",
    "However, at least in some patients, the decline occurs even without any detectable immune response.\n",
    "\n",
    "In 1996 Andrew Phillips proposed another explanation for the decline in this paper: \"Reduction of HIV Concentration During Acute Infection: Independence from a Specific Immune Response\", available from <https://people.math.gatech.edu/~weiss/uploads/5/8/6/1/58618765/phillips1996.pdf>).\n",
    "\n",
    "Phillips presents a system of differential equations that models the concentrations of the HIV virus and the CD4 cells it infects.\n",
    "The model does not include an immune response; nevertheless, it demonstrates behavior that is qualitatively similar to what is seen in patients during the first few weeks after infection.\n",
    "\n",
    "His conclusion is that the observed decline in the concentration of HIV might not be caused by an immune response; it could be due to the dynamic interaction between HIV and the cells it infects.\n",
    "\n",
    "In the repository for this book, you will find a notebook, *hiv_model.ipynb*, which you can use to implement Phillips's model and consider whether it does the work it is meant to do.\n",
    "You can download it from <https://github.com/AllenDowney/ModSimPy/raw/master/examples/hiv_model.ipynb> or run it on Colab at <https://colab.research.google.com/github/AllenDowney/ModSimPy/blob/master/examples/hiv_model.ipynb>."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "international-button",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
